﻿using HalconDotNet;
using HWindow_Tool.Control;
using LD.Host;
using LD.Vision;
using System;
using System.Collections.Generic;

namespace LD.Tool
{
    [Tool(FrmParam = "ToolTemplateMatchHightFrm", Text = "高精度匹配", ToolType = ToolEnum.Vision)]
    class ToolTemplateMatchHight : BaseTool
    {
        private HImage img;
        public override OpResult Execute(TB_Tool model)
        {
            try
            {
                stopwatch.Start();
                if (model.Param != null)
                {
                    var _param = Newtonsoft.Json.JsonConvert.DeserializeObject<ToolTemplateMatchParam>(model.Param);
                    if (!string.IsNullOrEmpty(_param.ImageSource))
                    {
                        img = (HImage)base.GetToolValue(model, _param.ImageSource);
                        if (img != null)
                        {
                            HWindow_Final hwindow = null;
                            if (!string.IsNullOrEmpty(_param.CameraName) && FrmVisionMain.Instance.HWindow.ContainsKey(_param.CameraName))
                                hwindow = FrmVisionMain.Instance.HWindow[_param.CameraName];

                            var opResult = TemplateHelper.FindTemplate(hwindow, img, _param.TemplateModel);
                            isSuccess = opResult.IsSuccess;
                            if (isSuccess)
                            {
                                匹配结果 = opResult.Append as TemplateResultModel;
                            }
                        }
                        else
                            Log(model, "图像不能为空", LogLevel.严重);
                    }
                    else
                        Log(model, "图像不能为空", LogLevel.严重);
                }
            }
            catch (Exception ex)
            {
                Log(model, ex.Message, LogLevel.严重);
            }
            finally
            {
                stopwatch.Stop();
            }
            return new OpResult() { IsSuccess = isSuccess, Message = message, ExecuteTime = stopwatch.ElapsedMilliseconds };
        }
        [Tool(Output = true)]
        public TemplateResultModel 匹配结果 { get; set; }
    }
}
